import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import static java.util.Base64.getDecoder;

/**
 * 认证信息拦截器
 */
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, @NonNull HttpServletResponse resp, @NonNull Object handler) throws Exception {
        //从请求头中获取认证信息，经过base64编码过的
        String base64AuthInfo = req.getHeader(AuthInfo.AUTH_INFO_HEADER_KEY);
        if (base64AuthInfo == null) {
            //尝试从请求参数中获取（针对特殊情况）
            base64AuthInfo = req.getParameter(AuthInfo.AUTH_INFO_HEADER_KEY);
        }
        if (StringUtils.hasText(base64AuthInfo)) {
            //base64解码
            String authInfo = new String(getDecoder().decode(base64AuthInfo));
            String[] arr = authInfo.split(":");
            //用户id，非主键
            String userId = arr[0];
            //用户名
            String userName = arr[1];
            //设置到当前线程中
            AuthInfo.setCurrent(AuthInfo.of(userId, userName));
        }
        return true;
    }
}
